from flask import render_template, Blueprint, request
from sqlalchemy.sql.functions import user

from apps.pojo.Entity import User,User_Schema

user_bp=Blueprint('user',__name__,url_prefix='/user')
user_schema=User_Schema(many=True)

@user_bp.route('/tolist')
def tolist():
    return render_template('user/list.html')
@user_bp.route('/list',methods=['GET','POST'])
def list():
# 接受分页参数    page 当前页  limit 每页显示的条数
   page=request.form.get('page',1,type=int)
   limit=request.form.get('limit',10,type=int)
# 查询用户表的记录数
   count=User.query.count()
# 查询用户表的数据
   offset = (page-1)*limit
   userList=User.query.offset(offset).limit(limit).all()
# 将集合转换为json
   users=user_schema.dump(userList)
#构建layui格式json对象
   return{
    "code":0,
    "msg":"查询成功",
    "count":count,
    "data":users
}



@user_bp.route('/toadd')
def toadd():
    return render_template('user/add.html')

@user_bp.route('/addSave', methods=['POST'])
def addSave():
    param = request.form
    user = User()
    user.username = param.get('username')
    user.password = param.get('password')
    user.sex = param.get('sex')
    try:
        # 保存用户到数据库
        db.session.add(user)
        # 提交事务
        db.session.commit()
        # 返回json数据
        return LayData.data2(200, '添加成功')
    except Exception as e:
        db.session.rollback()
        return LayData.data2(500, '添加失败')


@user_bp.route('/toupdate/<int:id>')
def toUpdate(id):
    user = User.query.filter(User.id == id).first()
    return render_template('user/edit.html', user=user)


@user_bp.route('/updateSave')
def toUpdate():
    param = request.form
    id = param.get('id')
    user = User.query.filter(User.id == id).first()
    user.username = param.get('username')
    user.password = param.get('password')
    user.sex = param.get('sex')
    try:
        db.session.commit()
        return LayData.data2(200, '修改成功')
    except Exception as e:
        db.session.rollback()
        return LayData.data2(500, '修改失败')